package com.gopi.remfilebrowser.gui;

import java.awt.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.SwingUtilities;

import com.gopi.utilities.gui.AbstractController;

public class FileBrowserController extends AbstractController
{
	private static FileBrowserController controller;
	private Map<String, List<Component>> actionComponents;
	private Map<String, Boolean> enableState;
	
	public static FileBrowserController getInstance()
	{
		return controller == null ? controller = new FileBrowserController() : controller;
	}

	public FileBrowserController()
	{
		actionComponents = new HashMap<String, List<Component>>();
		enableState = new HashMap<String, Boolean>();
	}
	
	@Override
	public void addActionCommand(String action, Component component) 
	{
		List<Component> components = actionComponents.get(action);
		if(components == null)
		{
			components = new ArrayList<Component>();
			actionComponents.put(action, components);
			Boolean b = enableState.get(action);
			if(b==null)
			{
				enableState.put(action,component.isEnabled());
			}
		}
		components.add(component);
	}

	@Override
	public boolean getStatus(String action) 
	{
		Boolean b = enableState.get(action);
		return b==null ? false : b.booleanValue();
	}

	@Override
	public void removeActionCommand(String action) 
	{
		List<Component> list = actionComponents.get(action);
		list.clear();
		actionComponents.remove(action);
		enableState.remove(action);
	}
	
	@Override
	public void setEnable(String action, boolean enable) 
	{
		updateComps(action, enable, 1);
	}

	@Override
	public void setVisible(String action, boolean enable) 
	{
		updateComps(action, enable, 2);
	}
	
	public void updateComps(final String action,final boolean enable,final int what)
	{
		final List<Component> list = actionComponents.get(action);
		if(list!=null)
		{
			enableState.put(action, enable);
			SwingUtilities.invokeLater(new Runnable() 
			{
				public void run()
				{
					for(Component component : list)
					{
						if(what==1)
							component.setEnabled(enable);
						else
							component.setVisible(enable);
					}
				}
			});
		}
	}
	
	
}
